#include "LoadTexture.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "Math.hpp"
#include <memory>
#include "gl.hpp"
#include "Exception.hpp"

using namespace std;

unsigned int LoadTexture(std::string filename)
{
	ivec2 resolution;
	int channels;
	auto image = unique_ptr<unsigned char, decltype(&stbi_image_free)>(
		stbi_load(filename.c_str(), &resolution.x, &resolution.y, &channels, 3),
		stbi_image_free);
	if(!image)
		THROW(Exception("Texture could not be loaded") << FilenameInfo(filename));

	GLuint texture;
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, resolution.x, resolution.y, 0,
				 GL_RGB, GL_UNSIGNED_BYTE, image.get());

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glGenerateMipmap(GL_TEXTURE_2D);

	return texture;
}
